package com.gameGroups.Controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.gameGroups.Dto.UserInfoDto;
import com.gameGroups.Dto.WorksDto;
import com.gameGroups.Dto.WorksExtDto;
import com.gameGroups.Service.UpdateUserInfoService;
import com.gameGroups.Service.WorksAndArticleService;
import com.gameGroups.Service.WorksUploadService;
import com.gameGroups.Utils.GetRandomNum;
import com.gameGroups.Utils.MyException;

@Controller
@RequestMapping("/works")
public class WorksUploadController {
	@Autowired
	private WorksUploadService worksUploadService;
	@Autowired
	private UpdateUserInfoService updateUserInfoService;
	@Autowired
	private WorksAndArticleService worksAndArticleService;
	//作品上传
    @RequestMapping(value="/saveWorks.do",method=RequestMethod.POST)
    @ResponseBody
	public Map<String,Object> saveWorks(@RequestParam(value="worksImg") MultipartFile files[], HttpServletRequest request,HttpServletResponse response) throws MyException{
      Map<String,Object> model=new HashMap<String, Object>();
      try {
          String basePath=System.getProperty("basePath");
          String title=request.getParameter("title");
          String pName=request.getParameter("pName");
          String description=request.getParameter("description");
          String worksContext=request.getParameter("worksContext");
          String worksType=request.getParameter("worksType");
          String suid=request.getParameter("uid");
          Integer uid= Integer.parseInt(suid);
          UserInfoDto userInfo = updateUserInfoService.queryUserInfo(uid.toString());
          String worksImg = uploadWorksUtil(files,basePath,uid.toString());
          WorksDto works=new WorksDto();
          works.setTitle(title);
          works.setHeadImg(userInfo.getHeadImg());
          works.setpName(pName);
          works.setDescription(description);
          works.setWorksContext(worksContext);
          works.setWorksType(worksType);
          works.setWorksImg(worksImg);
          works.setUid(uid);
          worksUploadService.saveWorks(works);
          model.put("status", "0000");  
	 } catch (Exception e) {
    	model.put("status", "9999");
		model.put("errorMessage", "系统异常!");
		throw new MyException("作品上传功能异常!"+":"+e);
	}
	  return model;
	}
   
    
    //作品留言
    @RequestMapping(value="/saveWorksExt.do",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> saveWorksExt(@RequestBody WorksExtDto worksExtDto,HttpServletRequest request,HttpServletResponse response) throws MyException{
    	 Map<String,Object> model=new HashMap<String, Object>();
    	 try {
	    	Integer layer=worksUploadService.queryWorksExtlayer(worksExtDto.getWid());
	    	layer=layer+1;			
	    	worksExtDto.setLayer(layer);
	    	worksUploadService.saveWorksExt(worksExtDto);
	  		model.put("status", "0000");  
		} catch (Exception e) {
	    	model.put("status", "9999");
			model.put("errorMessage", "系统异常!");
			throw new MyException("作品上传功能异常!"+":"+e);
		}
    	return model;
    }
    
    //作品删除
    @RequestMapping(value="/deleteWorks.do",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deleteWorks(HttpServletRequest request,HttpServletResponse response) throws MyException{
    	Map<String,Object> model=new HashMap<String, Object>();
    	try {
    		String basePath=System.getProperty("basePath");
        	String wid=request.getParameter("wid");	
    		WorksDto works = worksAndArticleService.queryWorks(wid);
        	worksUploadService.deleteWorks(wid);
        	worksUploadService.deleteWorksExt(wid);       	
        	String worksImg = works.getWorksImg();
        	String[] imgs = worksImg.split(",");
        	for (int i = 0; i < imgs.length; i++) {
            File file=new File(basePath+imgs[i]);
          	  if (file.exists()) {
          		  file.delete();
          	  }
			}
        	model.put("status", "0000");  
		} catch (Exception e) {
	    	model.put("status", "9999");
			model.put("errorMessage", "系统异常!");
			throw new MyException("作品删除功能异常!"+":"+e);
		}
    	return model;
    }
    
    
    private String uploadWorksUtil(MultipartFile files[], String basePath, String file){
        StringBuffer worksImg=new StringBuffer();
    	  if (files.length>0) {
        	String path =basePath+file;
        	for (int i = 0; i < files.length; i++) {
        		if (!files[i].isEmpty()) {
        			String fileName = files[i].getOriginalFilename();
        			String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());//获取文件后缀名
        			fileName=GetRandomNum.getNum(10)+fileSuffix;
        			String worksUrl="gameGroups/"+file+"/"+fileName;
        			if (i==0) {
        				worksImg.append(worksUrl);
  				    }else{
  					    worksImg.append(","+worksUrl);
  				    }
                	File targetFlie=new File(path,fileName);
                	if (!targetFlie.exists()) {
                		targetFlie.mkdirs();
        			}
                	try {
                	  files[i].transferTo(targetFlie);
        			} catch (Exception e) {
        			  e.printStackTrace();
        			}	
  				}				
  			} 
  		} 
    	return worksImg.toString();
    }
}
